import psutil
import time
import smtplib
from email.mime.text import MIMEText


def is_process_running():
    for proc in psutil.process_iter():
        if proc.name() == target_process:
            return True
    return False


def send_mail():
    # 创建邮件对象
    msg['Subject'] = 'Test Message'
    msg['From'] = '15932075391@163.com'
    msg['To'] = '2539491154@qq.com'

    # 设置服务器的地址和端口
    smtpobj = smtplib.SMTP_SSL('smtp.163.com', 465)
    # 向邮件服务器打招呼，这很重要
    smtpobj.ehlo()

    # 登录到smtp服务器
    smtpobj.login('15932075391@163.com', 'LSKEFHPOVATLNAJW')

    # 发送邮件
    smtpobj.sendmail(msg['From'], [msg['To']], msg.as_string())

    # 从smtp服务器断开
    smtpobj.quit()


if __name__ == '__main__':
    # 获得当前时间时间戳后转化为本地时间
    timeStruct = time.localtime(int(time.time()))
    # 日期格式 2023-02-11 06:45:21
    strTime = time.strftime("%Y-%m-%d %H:%M:%S", timeStruct)

    # 要监控的进程的名称
    print('please input the process(例子：notepad.exe) ', end='')
    target_process = input()
    # 选择监控模式
    print('please choose 1 程序运行发邮件 2 程序停止发邮件： ', end='')
    choice = int(input())

    if choice == 1:
        # 设置邮件正文内容
        msg = MIMEText(f'At {strTime}, the process of {target_process} has been started.')
        while True:
            is_running = is_process_running()
            if is_running:
                send_mail()
            else:
                print('Process is not running')

            # 每隔一段时间检查一次，例如每5秒
            time.sleep(10)

    elif choice == 2:
        # 设置邮件正文内容
        msg = MIMEText(f'At {strTime}, the process of {target_process} has been stop.')
        while True:
            is_running = is_process_running()
            if not is_running:
                send_mail()
            else:
                print('Process is running')

            # 每隔一段时间检查一次，例如每5秒
            time.sleep(10)
